import 'package:flutter/material.dart';

class FramesAnimation extends StatefulWidget {
  FramesAnimation({
    Key? key, // 定义组件状态的标识
    this.initIndex = 0,
    required this.images, // 传入播放的图片
  }) : super(key: key);

  final int initIndex;

  final List images;

  //const FramesAnimation({super.key});

  @override
  State<FramesAnimation> createState() => FramesAnimationState();
}

class FramesAnimationState extends State<FramesAnimation>
    with TickerProviderStateMixin {
  // 动画控制器
  late AnimationController _animationController;

  // 动画对象
  late Animation _animation;

  @override
  void initState() {
    // 创建动画控制器
    _animationController = AnimationController(
      // 动画时长
      duration: const Duration(milliseconds: 800),
      // 动画状态
      vsync: this,
    );

    // 创建动画对象
    _animation = Tween(
      begin: 0.0,
      end: (widget.images.length - 1).toDouble(),
    ).animate(_animationController);
    // 监听动画的状态
    _animationController.addListener(() {
      // 动画状态改变时, 重新构建页面
      setState(() {});
    });

    // 启动动画
    if (widget.initIndex == 0) {
      startAnimation();
    }

    super.initState();
  }

  // 启动动画方法
  void startAnimation() => _animationController.forward();

  // 重置动画方法
  void resetAnimation() => _animationController.reset();

  void disposeAnimation() => _animationController.dispose();

  @override
  void dispose() {
    // 释放动画资源
    _animationController.dispose();
    super.dispose();
  }

  //准备帧动画内容
  // List<Widget> frames = [
  //   Container(width: 20, height: 20, color: Colors.red),
  //   Container(width: 20, height: 20, color: Colors.orange),
  //   Container(width: 20, height: 20, color: Colors.yellow),
  //   Container(width: 20, height: 20, color: Colors.green),
  //   Container(width: 20, height: 20, color: Colors.cyan),
  //   Container(width: 20, height: 20, color: Colors.blue),
  //   Container(width: 20, height: 20, color: Colors.purple),
  // ];

  @override
  Widget build(BuildContext context) {
    // 测试 输入帧动画的取值
    // print(_animation.value);
    // int framesIndex = _animation.value.toInt();
    int framesIndex = _animation.value.floor();
    // return frames[framesIndex];
    return widget.images[framesIndex];
  }
}
